package com.alili_tv.system.utils;

import cn.hutool.jwt.JWT;
import lombok.val;

import java.util.Date;

public class JwtUtils {
    private static final String key = "ali_jwt_key";
    private static final long time = 1000 * 3600 * 24 * 3; // 3天

    /**
     * 生成token
     *
     * @return
     */
    public static String createToken(Long val) {
        Date date = new Date(System.currentTimeMillis() + time);

        // 默认使用HS265算法
        return JWT.create()
                .setPayload(key, val)
                .setExpiresAt(date)
                .setKey(key.getBytes())
                .sign();
    }

    /**
     * 验证token正确性和时效性
     *
     * @param jwtToken
     * @return
     */
    public static boolean validate(String jwtToken) {
        if (jwtToken == null || jwtToken.trim().equals("")) return false;
        return JWT.of(jwtToken).setKey(key.getBytes()).validate(0);
    }

    /**
     * 获取数据
     *
     * @param jwtToken
     * @return
     */
    public static Long getVal(String jwtToken) {
        if (jwtToken == null || jwtToken.trim().equals("")) {
            return null;
        }
        Long userId;
        try {
            userId = Long.parseLong(JWT.of(jwtToken).getPayload(key).toString());
        } catch (NumberFormatException e) {
            userId = null;
        }
        return userId;
    }
}
